package com.dongjiantong.app.controller.biz;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.model.EarMarks;
import com.dongjiantong.biz.service.EarMarksReadeService;
import com.dongjiantong.biz.service.EarMarksWriteService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.utils.UUIDUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;


/**
 * Created by ldf on 2017/11/15.
 */
@Slf4j
@OpenBean
public class EarMarkController {

    @Reference(version = "1.0.0")
    private EarMarksReadeService earMarksReadeService;

    @Reference(version = "1.0.0")
    private EarMarksWriteService earMarksWriteService;

    /**
     * todo 根据耳标库ID查询该耳标情况
     *
     * @param id 耳标库的ID主键
     * @return EarMarks
     */

    @OpenMethod(
            key = "app.EarMarks.findByID",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<EarMarks> findByID(Long id) throws IOException {

        if (id == null) {
            return Response.fail(HttpCode.BAD_REQUEST, "耳标库ID不能为null");
        } else {
            try {
                EarMarks earMarks = earMarksReadeService.selectByPrimaryKey(id);

                return Response.ok(earMarks);
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR, "查询出错请稍后再试");
            }


        }
    }

    /**
     * 根据养殖场ID 以下条件查询该养殖场所有的耳标list
     *
     * @param farmId     耳标库的养殖场ID
     * @param batch      批次
     * @param pageNum    页码
     * @param pageSize   一页数量
     * @param statusList 状态 -1、损坏（失效） 1、入库 2、佩标 3、出库
     * @return PageInfo<EarMarks>
     */
    @OpenMethod(
            key = "app.EarMarks.findByFarmId",
            paramNames = {"farmId", "pageNum", "pageSize", "statusList", "batch", "farmName"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<EarMarks>> findByFarmId(Long farmId, int pageNum, int pageSize, List<Integer> statusList,
                                                     String batch, String farmName) {


        try {
            if (farmId == null) {
                LoginInfo loginInfo = UserUtil.getCurrentUser();
                List<Long> list = loginInfo.getBreedFactoryIds();
                PageInfo<EarMarks> earMarksPageInfo = earMarksReadeService.selectByMap(farmId, pageNum, pageSize, statusList, batch, farmName, list);
                return Response.ok(earMarksPageInfo);
            }
            PageInfo<EarMarks> earMarksPageInfo = earMarksReadeService.selectByMap(farmId, pageNum, pageSize, statusList, batch, farmName, null);
            return Response.ok(earMarksPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR, "查询出错请稍后再试");
        }

    }


    /**
     * todo 根据养殖场ID 以下条件查询该养殖场所有的耳标list
     *
     * @param farmId   耳标库的养殖场ID
     * @param pageNum  页码
     * @param pageSize 一页数量
     * @return PageInfo<EarMarks>
     */
    @OpenMethod(
            key = "app.EarMarks.findByFarmIdAndListStatus",
            paramNames = {"farmId", "pageNum", "pageSize", "farmName"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo> findByFarmIdAndListStatus(Long farmId, int pageNum, int pageSize,
                                                        String farmName) {

        List<Map> mapList = new ArrayList<>();


        try {
//            PageInfo<EarMarks> pageInfo = earMarksReadeService.findByFarmIdAndListStatus(farmId, 1, 1000000, statusList, batch);
//
//            List<EarMarks> earMarkList = pageInfo.getList();
//            if (earMarkList.size() == 0) {
//                return Response.ok(mapList);
//            }
//            List<String> butch = new ArrayList<>();
//            for (EarMarks earMarks : earMarkList) {
//                butch.add(earMarks.getBatch());
//            }
//            List<String> butchS = new ArrayList<>(new HashSet<>(butch));
            PageInfo pageInfo = null;
            if (farmId == null) {
                LoginInfo loginInfo = UserUtil.getCurrentUser();
                List<Long> list = loginInfo.getBreedFactoryIds();
                if (list.size() != 0) {
                    pageInfo = earMarksReadeService.selectBatch(pageNum, pageSize, list, farmName);
                }

            } else {
                pageInfo = earMarksReadeService.selectBatch(pageNum, pageSize, farmId);
            }


            if (pageInfo == null) {
                return Response.ok(pageInfo);
            }
            List<String> butchS = pageInfo.getList();
            for (String bach : butchS) {
                EarMarks earMarks = new EarMarks();
                earMarks.setBatch(bach);
                List<EarMarks> butchMarch = earMarksReadeService.select(earMarks);
                List<String> numberList = new ArrayList<>();
                Integer remaining = 0;
                for (EarMarks earMarks1 : butchMarch) {
                    numberList.add(earMarks1.getMark_number());
                    if (earMarks1.getIs_selected() == 1) {
                        remaining++;
                    }
                }

                String min = Collections.min(numberList);
                Integer number = butchMarch.size();
                Map map = new HashMap();
                map.put("farmId", butchMarch.get(0).getFarm_id());
                map.put("farmName", butchMarch.get(0).getFarm_name());
                map.put("earType", butchMarch.get(0).getMark_type());
                map.put("bach", bach);
                map.put("min", min);
                map.put("number", number);
                map.put("remaining", remaining);
                map.put("date", butchMarch.get(0).getCreated_at());
                mapList.add(map);
            }
            pageInfo.setList(mapList);
            return Response.ok(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR, "查询出错请稍后再试");
        }

    }


    /**
     * todo 根据耳标号 和 耳标类型查询耳标信息
     *
     * @param markNumber 耳标号
     * @param markType   耳标类型 标识类型 比如1、猪 。。。。
     * @return EarMarks
     */
    @OpenMethod(
            key = "app.EarMarks.findByNumber",
            paramNames = {"markNumber", "markType"},
            httpMethods = RequestMethod.GET)
    public Response<EarMarks> findByNumber(String markNumber, int markType) {

        if (markNumber == null || markNumber.equals("")) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "耳标号输入不正确");
        }
        EarMarks earMarks = new EarMarks();
        earMarks.setMark_number(markNumber);
        earMarks.setMark_type(markType);

//        if (earMarks == null) {
//            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR, "耳标号不存在");
//        }
        try {
            EarMarks earMarksPut = earMarksReadeService.selectOne(earMarks);
            return Response.ok(earMarksPut);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR, "查询出错请稍后再试");
        }

    }

    /**
     * 根据养殖场起始耳标查询
     * @param number
     * @param farmId
     * @param sum
     * @return
     */
    @OpenMethod(
            key = "app.EarMarks.selectByStatusNumber",
            paramNames = {"number", "farmId","sum","status"},
            httpMethods = RequestMethod.GET)
    public Response<List> selectByStatusNumber(String number, Long farmId, Integer sum,Integer status) {
        return Response.ok(earMarksReadeService.selectByStatusNumber(number, farmId, sum,status));
    }


    /**
     * 模糊
     * @param number
     * @param farmId
     * @return
     */
    @OpenMethod(
            key = "app.EarMarks.selectByLikeNumber",
            paramNames = {"number", "farmId","sum","status"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo> selectByLikeNumber(String number, Long farmId,int pageNum, int pageSize) {
        return Response.ok(earMarksReadeService.selectByLikeNumber(number, farmId, pageNum,pageSize));
    }
    /**
     * todo 创建
     * 单独一个耳标入库
     *
     * @param earMarks
     * @return
     */

    @OpenMethod(
            key = "app.EarMarks.createEarMarkOne",
            paramNames = {"earMarks"},
            httpMethods = RequestMethod.POST)
    public Response<String> createEarMarkOne(EarMarks earMarks) {


        if (earMarks == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST, "耳标数据为空无法插入");
        }

        //验证耳标有没有重复
        EarMarks earMarksNew = new EarMarks();
        earMarksNew.setMark_number(earMarks.getMark_number());
        EarMarks earMarks1 = earMarksWriteService.selectOne(earMarksNew);
        if (earMarks1 != null) {

            throw new OPServerException(HttpCode.BAD_REQUEST, earMarks.getMark_number() + ",该耳标已经被使用");
        }

        //插入数据
        Long result = earMarksWriteService.insert(earMarks);
        Long a = earMarks.getId();
        if (result == 0) {
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL, "耳标插入失败请重试！");
        }

        return Response.ok("耳标入库成功");
    }


    /**
     * todo 创建
     * 多个耳标入库
     *
     * @param earMarksList
     * @param numberMany
     * @return
     */

    @OpenMethod(
            key = "app.EarMarks.createEarMarkMany",
            paramNames = {"earMarksList", "numberMany"},
            httpMethods = RequestMethod.POST)
    public Response<Map> createEarMarkMany(List<Map> earMarksList, List<String> numberMany) {


        List<EarMarks> earMarksRepeat = earMarksReadeService.selectByRepetitionNumber(numberMany);
        List<String> numberList = new ArrayList<String>();
        if (earMarksRepeat.size() != 0) {
            for (EarMarks earMarks : earMarksRepeat) {
                numberList.add(earMarks.getMark_number());
            }
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL, numberList.toString() + "这些耳标已经被使用");
        }
        Date date = new Date();
        Long butch = UUIDUtil.getGId();
        List<EarMarks> list = new ArrayList();
        for (Map map : earMarksList) {
            EarMarks earMarks = new EarMarks();
            earMarks.setMark_number((String) map.get("mark_number"));
            earMarks.setMark_type((Integer) map.get("mark_type"));
            earMarks.setStatus((Integer) map.get("status"));
            earMarks.setFarm_id(new Long((Integer) map.get("farm_id")));
            earMarks.setFarm_name((String) map.get("farm_name"));
            earMarks.setBatch(butch.toString());
            earMarks.setIs_selected(1);
            earMarks.setCreated_at(date);
            list.add(earMarks);
        }
        int result = earMarksWriteService.insertList(list);
        if (result != earMarksList.size()) {
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL, "入库失败请稍后再试");
        }
        Map map = new HashMap();
        map.put("data", earMarksList.size() + "个耳标入库成功");
        return Response.ok(map);
    }


    /**
     * todo 更新
     * 更新耳标库 （单个）
     *
     * @param earMarks
     * @return
     */

    @OpenMethod(
            key = "app.EarMarks.updateEarMarkByOne",
            paramNames = {"earMarks"},
            httpMethods = RequestMethod.POST)
    public Response<String> updateEarMarkByOne(EarMarks earMarks) {


        if (earMarks.getFarm_id() == null) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "养殖场id不能为空");
        }
        if (earMarks.getMark_number() == null) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "耳标号不能为空");
        }

        int result = earMarksWriteService.updateByPrimaryKeySelective(earMarks);
        if (result == 0) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "更新失败请稍后再试");
        }
        return Response.ok("更新成功");
    }

    @OpenMethod(
            key = "app.EarMarks.updateEarMarkByStatus",
            paramNames = {"earMarks", "earNumber", "status"},
            httpMethods = RequestMethod.POST)
    public Response<Map> updateEarMarkByStatus(EarMarks earMarks, String earNumber, Integer status) {

        //验证耳标有没有重复
        EarMarks earMarksNe = new EarMarks();
        earMarksNe.setMark_number(earNumber);
        EarMarks earMarks1 = earMarksWriteService.selectOne(earMarksNe);
        if (earMarks1 != null) {
            if (earMarks1.getFarm_id() != earMarks.getFarm_id()) {
                throw new OPServerException(HttpCode.BAD_REQUEST, earNumber + ",该耳标已经被使用");
            } else {
                if (earMarks1.getStatus() != 1) {
                    throw new OPServerException(HttpCode.BAD_REQUEST, earNumber + ",该耳标不能被更换");
                }

            }

        }

        if (earMarks.getFarm_id() == null) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "养殖场id不能为空");
        }
        if (earNumber == null) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "耳标号不能为空");
        }
        if (status == null) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "状态不能为空");
        }
        try {
            if (earMarks1.getStatus() == 1) {

            } else {
                // 创建耳标
                EarMarks earMarksNew = earMarksReadeService.selectByPrimaryKey(earMarks.getId());
                earMarksNew.setId(null);
                earMarksNew.setIs_selected(1);
                earMarksNew.setMark_number(earNumber);
                earMarksWriteService.insert(earMarksNew);

            }

            //将原有耳标设为损坏状态
            earMarks.setStatus(status);
            int result = earMarksWriteService.updateByPrimaryKeySelective(earMarks);

            if (result == 0) {
                throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "更新失败请稍后再试");
            }
            Map map = new HashMap();
            map.put("data", "耳标更新成功");
            return Response.ok(map);

        } catch (Exception e) {
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "更新失败请稍后再试");
        }


    }


    /**
     * todo 更新
     * 更新耳标库 （多个）
     *
     * @param earMarksList
     * @return
     */
    @OpenMethod(
            key = "app.EarMarks.updateEarMarkBySome",
            paramNames = {"earMarksList"},
            httpMethods = RequestMethod.POST)
    public Response<String> updateEarMarkBySome(List<EarMarks> earMarksList) {
        try {

            for (EarMarks earMarks : earMarksList) {
                if (earMarks.getFarm_id() == null) {
                    throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "《养殖场id不能为空》" + earMarks.toString());
                }
                if (earMarks.getMark_number() == null) {
                    throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "《耳标号不能为空》" + earMarks.toString());
                }
                earMarksWriteService.updateByPrimaryKeySelective(earMarks);
            }
            return Response.ok("更新成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL, "更新失败请稍后再试");
        }

    }


}




